import jwt from 'jsonwebtoken';

import { JWT_CONFIG } from '../config/constant';

export interface JwtToken {
  token: string;
  expiresIn: number;
}

export interface User {
  id: string;
}

export class AuthService {

  // sign 生成 token
  public createToken(user: User): JwtToken {
    const expiresIn = JWT_CONFIG.EXPIRES_IN;
    const secret = JWT_CONFIG.SECRET;
    const token = jwt.sign(user, secret, { expiresIn });
    return {
      token,
      expiresIn: expiresIn * 1000 + +new Date() + 8 * 60 * 60 * 1000
    };
  }

  public verifyToken(token: string): any {

    try {
      const decoded = jwt.verify(token, JWT_CONFIG.SECRET);
      console.log(decoded);
      return decoded;
    } catch (err) {
      return false;
    }
  }

}


